import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { login } from '@/api/user'

export const userMode = defineStore('userMode', () => {
    const user = ref<null | object>(null);
    const token = ref<null | string>(null);

    const userlogin = async (userInfo: any) => {
        let res = { //  模拟数据，删除即可
            data: {
                token: '*wm$yy^vDUVEq0sp',
                user: {
                    id: 1,
                    username: 'admin',
                    nickname: '管理员',
                    roles: ['admin']
                }
            }
        }
        try {
            res = await login(userInfo)
        } catch (err) { }
        token.value = res?.data.token
        user.value = res?.data.user
        localStorage.setItem('token', res?.data.token)
        localStorage.setItem('user', JSON.stringify(res?.data.user))
        localStorage.setItem('theme', 'light')
        return token.value

    }

    const clearUser = () => {
        token.value = null
        user.value = null
        localStorage.removeItem('token')
        localStorage.removeItem('user')
    }

    return { user, token, userlogin, clearUser }
})